/**
 * 跳跃控制
 */

 export default class Control extends Laya.Script {

    constructor() { super() }

    private sprite: Laya.Sprite // 精灵

    private pressTimer: number = 0 // 蓄力时间

    private coldDownTimer: number = 300 // 两次跳跃最小间隔

    private lastTimer: number = 0 // 上一次跳跃的时间

    private can_jump: boolean = false // 是否可以跳跃

    private can_play: boolean = false // 是否可以播放动效

    private partIns: Laya.Particle2D // 动效实例

    onEnable(): void {
        Laya.MouseManager.multiTouchEnabled=false // 关闭多点触控

        this.sprite = this.owner as Laya.Sprite

        this.sprite.on(Laya.Event.MOUSE_DOWN, this, this.mouseDown)
        this.sprite.on(Laya.Event.MOUSE_UP, this, this.mouseUp)

        // 按住的粒子效果
        Laya.loader.load('animation/press.part', Laya.Handler.create(this, this.onAssetsLoaded), null, Laya.Loader.JSON);

        this.addListener()
    }

    onDisable(): void {
        if (this.partIns) {
            this.partIns.destroy()
        }
    }

    // 资源加载完成
    private onAssetsLoaded(): void {
        this.can_play = true
    }

    // 监听事件
    private addListener(): void {
        let vm = this
        // 跳跃结束
        Laya.stage.on("jump_end", this, function () {
            vm.can_jump = true
        });
    }

    // 按下开始蓄力
    private mouseDown(e: Laya.Event): void {

        this.pressTimer = Date.now()
        this.playEff()
        
    }

    // 放开开始跳跃
    private mouseUp(): void {
        this.stopEff()
        
        
        let date = Date.now()
        if (!this.can_jump) return
        if (date - this.lastTimer < this.coldDownTimer) return
        this.lastTimer = date
        let diff:number = date - this.pressTimer
        if (diff > 1000) diff = 1000 // 最长按下1s
        if (diff < 300) diff = 300 // 最短按下300ms
        let power:number = Math.ceil(diff / 100)
        let params = {
            dir: this.sprite.name == '右按钮',
            power: power
        }
        Laya.stage.event("jumping", params)
        this.can_jump = false
    }

    // 播放粒子效果
    private playEff(): void {
        if (!this.can_play) return
        if (this.partIns) {
            this.partIns.destroy()            
        }
        // 粒子效果
        let settings = Laya.loader.getRes('animation/press.part');
		this.partIns = new Laya.Particle2D(settings);
        this.sprite.addChild(this.partIns);
        this.partIns.scale(0.5, 0.5)
        this.partIns.pivot(-100, -100)
		this.partIns.x = 0;
        this.partIns.y = 0;
        
        // 按键效果
        Laya.Tween.to(this.sprite, {scaleX: 1.1}, 200, Laya.Ease.circIn)
    }

    // 停止播放粒子效果
    private stopEff(): void {
        if (!this.can_play) return  
        if (this.partIns) {
            this.partIns.destroy()            
        }
        Laya.Tween.to(this.sprite, {scaleX: 1}, 200, Laya.Ease.circOut)
    }

 }